import { Pressable, StatusBar, StyleSheet, Text, View, Image, ScrollView } from 'react-native';
import React, { useState, useEffect, useRef } from 'react';
import Icon from 'react-native-vector-icons/Ionicons';
import LinearGradient from 'react-native-linear-gradient';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import { useNavigation, useRoute } from '@react-navigation/native';
import { useTranslation } from 'react-i18next';
import { px2dp, scale, width } from '~/utils/px2dp';
import { deviceStore, observer, webSocketStore } from '~/store';
import { getHandsValue, saveHandsValue } from '~/api/deviceApi';
import { openHeart, isOpenRealtimeData } from '~/utils/ble/application';
import { useTimeout } from '~/common';
import { MyLoading } from '~/components';

const OpenHeart = observer(() => {
    const insets = useSafeAreaInsets();
    const { t } = useTranslation();
    const router = useRoute<any>();
    const loadingRef = useRef<any>();
    const [isTimeout, startTimer, resetTimer] = useTimeout(60); // 获取超时相关
    const { type, device_sn, subDevice_sn, device_code } = router.params || {};
    const navigation: any = useNavigation();
    const { heartStatus, heartValue } = deviceStore.heart;
    const { linkSubDeviceStatus } = webSocketStore;

    // 获取用户设置手动心率
    const [heart, setHeart] = useState(0);
    const getValue = () => {
        getHandsValue({ type: 1, device: subDevice_sn }).then((res) => {
            setHeart(res.data.value);
        });
    };
    const startHeart = () => {
        if (linkSubDeviceStatus == 0 && deviceStore.device.connectedDeviceStatus == 0) {
            Toast.show({ content: t('OpenHeart.t13') });
            return;
        }
        startTimer();
        if (heartStatus) {
            openHeart(0, router.params);
        } else {
            openHeart(1, router.params);
        }
    };

    useEffect(() => {
        resetTimer();
        loadingRef.current.hideLoading();
        isOpenRealtimeData(1, router.params);
    }, [heartStatus]);

    const saveHeartValue = () => {
        saveHandsValue({ device: subDevice_sn, type: 1, value: heartValue });
    };
    useEffect(() => {
        getValue();
        return () => {
            if (heartValue > 0) {
                saveHeartValue();
            }
        };
    }, []);

    useEffect(() => {
        if (isTimeout) {
            Toast.show({ content: t('OpenHeart.t14') });
            loadingRef.current.hideLoading();
            resetTimer();
            deviceStore.heart.heartStatus = false;
            deviceStore.heart.heartValue = 0;
        }
    }, [isTimeout]);

    const renderLine = (color) => {
        return (
            <View style={{ flexDirection: 'column', justifyContent: 'space-between', width: 1, height: px2dp(50) }}>
                <View style={{ width: 1, height: px2dp(5), backgroundColor: color }} />
                <View style={{ width: 1, height: px2dp(5), backgroundColor: color }} />
                <View style={{ width: 1, height: px2dp(5), backgroundColor: color }} />
                <View style={{ width: 1, height: px2dp(5), backgroundColor: color }} />
                <View style={{ width: 1, height: px2dp(5), backgroundColor: color }} />
                <View style={{ width: 1, height: px2dp(5), backgroundColor: color }} />
            </View>
        );
    };

    return (
        <LinearGradient colors={['#F3FCFF', '#DBF9FB']} style={styles.container}>
            <StatusBar translucent={true} backgroundColor={'#F3FCFF'} />
            <View style={[styles.row, styles.between, { marginLeft: px2dp(32), marginTop: insets.top }]}>
                <Pressable onPress={() => navigation.goBack()}>
                    <Icon name="chevron-back-outline" size={26} color={'#000'}></Icon>
                </Pressable>
                <Text style={styles.title}>{t('OpenHeart.title')}</Text>
                <View />
            </View>
            <ScrollView contentContainerStyle={styles.contentContainerStyle} showsVerticalScrollIndicator={false}>
                <View style={styles.cover_container}>
                    <Image
                        source={{
                            uri: 'https://bjy-dev.oss-cn-shenzhen.aliyuncs.com/xcx/img/01C-xinlvkaiqi.png?1',
                        }}
                        style={styles.cover}
                    />
                    <View style={[styles.row, styles.between, styles.menue]}>
                        <View>
                            <Text>{t('OpenHeart.t4')}(bpm)</Text>
                            <Text style={styles.t1}>{heart > 0 ? heart : t('OpenHeart.t1')}</Text>
                        </View>
                        <View>
                            <Text>{t('OpenHeart.t5')}(bpm)</Text>
                            <Text style={styles.t1}>
                                {heartValue > 0 ? heartValue : heartStatus ? t('OpenHeart.t2') : t('OpenHeart.t3')}
                            </Text>
                        </View>
                    </View>
                    <View style={styles.list_menue}>
                        <Text style={[styles.progressTxtTwo, { left: px2dp(20) }]}>{'<20'}</Text>
                        <Text style={[styles.progressTxtTwo, { left: px2dp(190) }]}>{'60'}</Text>
                        <Text style={[styles.progressTxtTwo, { left: px2dp(370) }]}>{'100'}</Text>
                        <Text style={[styles.progressTxtTwo, { right: px2dp(20) }]}>{'>200'}</Text>
                        <View style={styles.progress}>
                            {renderLine('#C4C4C4')}
                            <View style={styles.low}>
                                <Text style={styles.progressTxt}>{t('OpenHeart.t6')}</Text>
                            </View>
                            {renderLine('#C4C4C4')}
                            <View style={styles.normal}>
                                <Text style={styles.progressTxt}>{t('OpenHeart.t7')}</Text>
                            </View>
                            {renderLine('#FF4E4E')}
                            <View style={styles.high}>
                                <Text style={styles.progressTxt}>{t('OpenHeart.t8')}</Text>
                            </View>
                            {renderLine('#FF4E4E')}
                        </View>

                        <Pressable style={styles.btn} onPress={startHeart}>
                            <Image
                                style={styles.icons}
                                source={{
                                    uri: heartStatus
                                        ? 'https://bjy-dev.oss-cn-shenzhen.aliyuncs.com/xcx/images/openBtn.png'
                                        : 'https://bjy-dev.oss-cn-shenzhen.aliyuncs.com/xcx/images/closeBtn.png',
                                }}
                            />
                            <Text>{heartStatus ? t('OpenHeart.t9') : t('OpenHeart.t10')}</Text>
                        </Pressable>
                    </View>
                </View>
            </ScrollView>
            <MyLoading ref={loadingRef} title={heartStatus ? t('OpenHeart.t11') : t('OpenHeart.t12')} />
        </LinearGradient>
    );
});

export default OpenHeart;

const styles = StyleSheet.create({
    row: {
        flexDirection: 'row',
        alignItems: 'center',
    },
    between: {
        justifyContent: 'space-between',
    },
    container: {
        flex: 1,
        // paddingTop: isIos() ? statusBarHeight * 3 : statusBarHeight * 1.6,
    },
    title: {
        fontSize: scale(28),
        color: '#000',
        fontWeight: 'bold',
    },
    cover_container: {
        flex: 1,
        alignItems: 'center',
        marginTop: '30%',
    },
    cover: {
        resizeMode: 'contain',
        width: px2dp(500),
        height: px2dp(500),
    },
    contentContainerStyle: {
        flexGrow: 1,
    },
    menue: {
        width: width - px2dp(64),
        marginHorizontal: px2dp(32),
        marginTop: '20%',
    },
    t1: {
        marginTop: px2dp(24),
        textAlign: 'center',
    },
    list_menue: {
        backgroundColor: '#fff',
        paddingTop: px2dp(24),
        marginTop: px2dp(64),
        height: '100%',
        width: width,
    },
    progressTxtTwo: {
        color: '#666666',
        fontSize: scale(20),
        position: 'absolute',
        top: px2dp(75),
    },
    progress: {
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'center',
    },
    low: {
        width: px2dp(182),
        height: px2dp(50),
        backgroundColor: 'rgba(37, 196, 205, 0.2)',
        justifyContent: 'center',
        alignItems: 'center',
    },
    progressTxt: {
        color: '#666666',
        fontSize: scale(24),
    },

    normal: {
        width: px2dp(180),
        height: px2dp(50),
        backgroundColor: 'rgba(29, 206, 135, 0.2)',
        justifyContent: 'center',
        alignItems: 'center',
    },

    high: {
        width: px2dp(340),
        height: px2dp(50),
        backgroundColor: 'rgba(255, 126, 86, 0.2)',
        justifyContent: 'center',
        alignItems: 'center',
    },
    btn: {
        justifyContent: 'center',
        alignItems: 'center',
        marginTop: '20%',
    },
    issue: {
        width: px2dp(38),
        height: px2dp(38),
        marginLeft: px2dp(4),
        marginBottom: px2dp(24),
    },
    icons: {
        width: px2dp(80),
        height: px2dp(80),
    },
});
